<template>
  <div class="app-container">
    <el-form ref="formRef" :model="form" :rules="rules">
      <el-row class="el-top">
<!--        <el-col :span="3">-->
<!--          <el-form-item class="ml20 mt8 mr20" label="入库方式:" prop="importClass">-->
<!--            <el-select v-model="form.importClass" disabled placeholder="请选择入库方式">-->
<!--              <el-option v-for="(dict, index) in typeList" :key="dict.dictValue" :label="dict.dictLabel"-->
<!--                         :value="dict.dictValue"/>-->
<!--            </el-select>-->
<!--          </el-form-item>-->
<!--        </el-col>-->
        <el-col :span="4">
          <el-form-item class="ml20 mt8" label="供货单位:" prop="storageFrom">
            <drug-storage-info ref="drugStorageDeptRef" :drug-fromLevel-str="'0'"
                               :org-id="queryParams.orgId"
                               :value="form.storageFrom" :value-storage-id="form.storageFrom"
                               class="import-master" style="width: 180px"
                               @drugStorageChange="storageFromClick"/>
<!--            <drug-storage-dept ref="drugStorageDeptRef" :org-id="queryParams.orgId"-->
<!--                               :value="form.storageFrom"-->
<!--                               :value-storage-id="form.storageFrom" class="import-master"-->
<!--                               style="width: 180px"-->
<!--                               @drugStorageChange="storageFromClick"/>-->
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item class="ml20 mt8" label="申领科室:" prop="storageId">
            <drug-storage-dept ref="storageIdDeptRef" :org-id="queryParams.orgId"
                               :disabled="true" :value-storage-id="form.storageId"
                               class="import-master" @drugStorageChange="storageIdClick"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <!-- 入库编辑列表 -->
        <el-table :border="true" :data="form.detailList" :header-cell-style="$headerCellStyle"
                  header-cell-class-name="requiredClass">
          <el-table-column :align="'center'" fixed="left" label="药品名称" min-width="168px" prop="drugName">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.itemInfo'" class="table-form-margin">
                <!-- 入库药品检索 -->
                <el-input v-if="scope.row.isShow" v-model="scope.row.drugName"
                          @focus="isShowItemNameFocus(scope.$index, scope.row)">
                </el-input>
                <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                                      :table-head-list="tableHeadList" :title="itemTitle"
                                      :width="730" style="width: 100%"
                                      @itemNameInput="itemNameInput" @rowClick="rowClick($event, 0)"/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领数量" prop="quantity"
                           width="210px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.quantity'" :rules="rules.quantity"
                            class="table-form-margin">
                <el-input v-model="scope.row.quantity" clearable>
                  <template #append>
                    <dict-data-tag :options="dictDataMap['spec_unit']"
                                   :value="scope.row.currentUnits"/>
                  </template>
                </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注" prop="remarks"
                           width="210px">
            <template #default="scope">
              <el-form-item :prop="'detailList.' + scope.$index + '.remarks'"
                            class="table-form-margin">
                <el-input v-model="scope.row.remarks" clearable/>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码" prop="drugCode"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                           width="200px"/>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作"
                           width="80px">
            <template #default="scope">
              <el-tooltip class="item" content="添加" effect="dark" placement="top">
                <el-button circle type="primary" @click="handleAdd">
                  <template #icon>
                    <i-ep-plus/>
                  </template>

                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>

      </el-row>
      <el-row class="mt5">
        <el-col :span="1.5" class="mr10">
          <span class="mr20">待入库药品</span>
          <el-button style="margin-bottom: 3px" type="primary" @click="temporaryStorage">
            <template #icon>
              <i-ep-FolderOpened/>
            </template>
            暂存
          </el-button>
        </el-col>
        <el-col :span="1.5" class="mr10">
          <el-button :disabled="buttonLoading" type="info" @click="temporaryStorageTableClick">
            <template #icon>
              <i-ep-memo/>
            </template>
            申领列表
          </el-button>
        </el-col>
        <el-col :span="2" class="mr10">
          <el-button :disabled="buttonLoading" type="success" @click="lastSave">
            <template #icon>
              <i-ep-FolderOpened/>
            </template>
            确认发送
          </el-button>
        </el-col>
        <!--        <el-col :span="8">-->
        <!--          <span style="color: #fd0101;font-size: 13px">入库发票号：</span>-->
        <!--          <el-input v-model="form.invoiceNo" clearable style="width: 180px"/>-->
        <!--        </el-col>-->
        <el-table v-adaptive="120" :border="true" :data="form.detailListSave" :header-cell-style="$headerCellStyle"
                  highlight-current-row>
          <el-table-column :align="'center'" fixed="left" label="序号" prop="index" width="100px">
            <template #default="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column :align="'center'" fixed="left" label="药品名称" min-width="175px" prop="drugName"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领数量" prop="quantity"
                           width="230px">
            <template #default="scope">
              <div>
                <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.currentUnits"
                               class="mb-10 mr10"
                               style="float: right"/>
                <div class="mr20" style="float: right; font-weight: bold">
                  {{ scope.row.quantity }}
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注" prop="remarks"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编码" prop="drugCode"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                           width="200px"/>
          <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                           width="200px"/>
          <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                           label="操作"
                           width="90px">
            <template #default="scope">
              <el-tooltip class="item" content="编辑" effect="dark" placement="left">
                <el-button v-hasPerm="['base:drugImportMaster:edit']" circle type="success"
                           @click="handleUpdate(scope.row, scope.$index)">
                  <template #icon>
                    <i-ep-edit/>
                  </template>

                </el-button>
              </el-tooltip>
              <el-tooltip class="item" content="删除" effect="dark" placement="top">
                <el-button v-hasPerm="['base:drugImportMaster:remove']" circle type="danger"
                           @click="handleDelete(scope.row, scope.$index)">
                  <template #icon>
                    <i-ep-delete/>
                  </template>

                </el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-row>
    </el-form>
    <el-dialog v-model="open" :close-on-click-modal="false" :title="'暂存列表'" append-to-body width="95%"
               @close="temporaryStorageClose()">
      <el-row :gutter="10">
        <el-col :span="9">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span class="mb5">申领主记录（点击列表可查看申领药品明细）</span>
              <el-row :gutter="10">
                <el-col :span="12">
                  <el-form-item label="申领单号" prop="applyNo">
                    <el-input v-model="queryParams.applyNo" class="width-120" clearable/>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="状态" prop="confirmType">
                    <el-select v-model="queryParams.confirmType" class="width-120" clearable @change="getList">
                      <el-option label="未确认" value="0"/>
                      <el-option label="确认出库" value="1"/>
                      <el-option label="已发送" value="2"/>
                      <el-option label="暂存" value="4"/>
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-form-item label="申领时间" prop="applyTime">
                  <el-date-picker v-model="dateRange" :unlink-panels="true" end-placeholder="结束日期"
                                  range-separator="截止" start-placeholder="开始日期" type="daterange"
                                  @change="timeChange"></el-date-picker>
                </el-form-item>
              </el-row>
              <el-button class="mb5" type="primary"
                         @click="getList">
                <template #icon>
                  <i-ep-search/>
                </template>
                刷新
              </el-button>
            </div>
            <div class="mb20">
              <el-table :border="true" :data="stagingList" :header-cell-style="$headerCellStyle" height="400"
                        @row-click="stagingMaster">
                <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="left"
                                 header-align="center" label="操作" width="80px">
                  <template #default="scope">
                    <el-tooltip class="item" content="引入"
                                v-if="scope.row.confirmType != '2'" effect="dark"
                                placement="top">
                      <el-button circle type="primary" @click.stop="bringIn(scope.row)">
                        <template #icon>
                          <i-ep-edit/>
                        </template>
                      </el-button>
                    </el-tooltip>
                    <el-tooltip class="item" content="删除"
                                v-if="scope.row.confirmType != '2'" effect="dark"
                                placement="top">
                      <el-button circle type="danger" @click.stop="deleteMaster(scope.row)">
                        <template #icon>
                          <i-ep-delete/>
                        </template>
                      </el-button>
                    </el-tooltip>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领单号"
                                 prop="applyNo"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="供货单位"
                                 prop="storageFromName"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领科室"
                                 prop="storageName"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领时间"
                                 min-width="130px"
                                 prop="applyTime"/>
                <el-table-column :align="'center'" fixed="right" label="状态" prop="confirmType" width="80px">
                  <template #default="scope">
                    <span v-if="scope.row.confirmType ==='0'" style="color:#d20303">未确认</span>
                    <span v-if="scope.row.confirmType ==='1'" style="color:#023aa4">确认出库</span>
                    <span v-if="scope.row.confirmType ==='2'" style="color:#027e1d">已发送</span>
                    <span v-if="scope.row.confirmType ==='4'" style="color:#a95602">暂存</span>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领操作人"
                                 min-width="90px"
                                 prop="createByName">
                </el-table-column>
              </el-table>
              <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                          v-model:page="queryParams.pageNum"
                          :total="total" @pagination="getList"/>
            </div>
          </el-card>
        </el-col>
        <el-col :span="15">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>申领明细</span>
            </div>
            <div class="mb20">
              <el-table :border="true" :data="stagingListDetail" :header-cell-style="$headerCellStyle" height="512">
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品编号"
                                 min-width="60px"
                                 prop="serialNumber"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="药品名称"
                                 min-width="180px"
                                 prop="drugName">
                  <template #default="scope">
                    <span class="fz14 fw-bold">{{ scope.row.drugName }}</span>
                  </template>
                </el-table-column>
                <!--                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量"-->
                <!--                                 min-width="90px"-->
                <!--                                 prop="packageNum"/>-->
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装规格"
                                 min-width="120px"
                                 prop="packageSpec"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领数量"
                                 min-width="90px"
                                 prop="quantity">
                  <template #default="scope">
                    <div>
                      <dict-data-tag v-if="scope.row.packSize === '2'" :options="dictDataMap['spec_unit']"
                                     :value="scope.row.packageUnits"
                                     class="mb-10 mr10" style="float: right"/>
                      <dict-data-tag v-else :options="dictDataMap['spec_unit']"
                                     :value="scope.row.minUnits"
                                     class="mb-10 mr10" style="float: right"/>
                      <div class="mr20" style="float: right; font-weight: bold">
                        {{ scope.row.quantity }}
                      </div>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家"
                                 min-width="120px"
                                 prop="firmName"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="申领时间"
                                 min-width="130px"
                                 prop="applyTime"/>
                <el-table-column :align="'center'" :show-overflow-tooltip="true" label="备注"
                                 min-width="130px"
                                 prop="remarks"/>
              </el-table>
              <pagination v-show="detailTotal > 0" v-model:limit="detailQuery.pageSize"
                          v-model:page="detailQuery.pageNum" :total="detailTotal"
                          @pagination="getListDetail"/>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {
  addDrugApplyFor,
  delDrugApplyFor,
  delDrugApplyForByApplyNo,
  listDrugApplyFor,
  selectPageDrugApplyFor
} from "@/api/drug/drugApplyFor.ts";
import {autoApplyForList} from "@/api/drug/drugStock";
import {quantityNumber, retailPriceV, tradePriceV} from "@/utils/myRules";
import {useUserStoreHook} from "@/store/modules/user";
import {useDictStoreHook} from "@/store/modules/dict";
import {autoApplyForArray, jsonStrInObj} from "@/utils/autoComplete";

const formRef = ref();
const storageIdDeptRef = ref();
const drugStorageDeptRef = ref();
const useUserStore = useUserStoreHook();
const {proxy} = getCurrentInstance() as any;
const date = proxy.$parseTime(new Date(), "{y}-{m}-{d} ");
const dateRange = ref([date + "00:00:00", date + "23:59:59"]);
const dictStore = useDictStoreHook();
const dictDataMap = ref(
  dictStore.isTypeGetData("drug_storage_type", "drug_payment_type", "price_ratio", "spec_unit")
);
// 是否清空主记录信息
const isEmptyApplyInfo = ref(true);
const currentSelectDept = proxy.$currentSelectDept
// 按钮loading
const buttonLoading = ref(false);
// 登录用户信息
const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
const itemAutomatic = ref();
// 暂存列表
const stagingList = ref<any>([]);
// 暂存申领明细列表
const stagingListDetail = ref<any>([]);
// 判断是否可申领
const isImport = ref(true);
// 总条数
const total = ref(0);
// 明细总条数
const detailTotal = ref(0);
// 是否显示暂存列表弹出层
const open = ref(false);
// 入库方式list
const typeList = ref<any>([]);
// 表单参数
const form = ref<any>({
  importClass: "12",
  isStaging: "Y",
  storageFrom: "",
  storageId: "",
  invoiceNo: "",
  detailList: [
    {
      expireDate: "",
      discount: "1",
      itemInfo: "",
      infoId: "",
      drugName: "",
      drugCode: "",
      orgId: "",
      packageSpec: "",
      packageUnits: "",
      tradePrice: "",
      retailPrice: "",
      firmId: "",
      firmName: "",
      packageNum: "",
      drugPriceId: "",
      trackCodes: ""
    },
  ],
  detailListSave: [],
});
// 暂存列表查询参数
const detailQuery = ref<any>({
  pageNum: 1,
  pageSize: 10,
  applyId: "",
});
const queryParams = ref<any>({
  pageNum: 1,
  pageSize: 10,
  orgId: undefined,
});
// 项目选择自动补全窗体名称
const itemTitle = ref("药品选择");
// 项目选择自动补全表格表头
const tableHeadList = ref<any>(jsonStrInObj(autoApplyForArray));
// 项目选择自动补全表格数据
const tableBodyList = ref<any>([]);
// 项目选择自动补全字典数组
const dictArray = ref(["spec_unit"]);

// 表单校验
const rules = ref({
  tradePrice: [{required: true, validator: tradePriceV, trigger: "change"}],
  retailPrice: [{required: true, validator: retailPriceV, trigger: "change"}],
  importClass: [{required: true, message: "入库方式不能为空", trigger: "change"}],
  discount: [{required: true, message: "比例不能为空", trigger: "change"}],
  storageId: [{required: true, message: "申领科室不能为空", trigger: "blur"}],
  quantity: [{required: true, validator: quantityNumber, trigger: "blur"}],
});


if (userInfo.orgId) {
  queryParams.value.orgId = userInfo.orgId;
}
if (!currentSelectDept) {
  // isImport.value = false;
  ElMessage.error("请选择库存药房后，再进行申领操作。");
} else {
  isImport.value = true;
  form.value.storageId = currentSelectDept;
  // getStoreroomDistinguishFun();
}

function timeChange(e) {
  if (e) {
    dateRange.value = [proxy.$parseTime(e[0], "{y}-{m}-{d} 00:00:00"), proxy.$parseTime(e[1], "{y}-{m}-{d} 23:59:59")]
  }
  getList()
}

/** 项目名称自动补全检索 */
function itemNameInput(event, _value) {
  if (!form.value.storageFrom) {
    return ElMessage.error("请选择供货单位");
  }
  form.value.itemName = event;
  autoApplyForListFun();
}

/** 申领药品检索 */
function autoApplyForListFun() {
  const data = {
    orgId: queryParams.value.orgId,
    storageId: form.value.storageFrom,
    itemInfo: form.value.itemName
  }
  autoApplyForList(data).then((res: resType) => {
    tableBodyList.value = res.data;
    itemAutomatic.value.init();
  })
}

/** 药品自动补全点击事件 */
function rowClick(obj, index) {
  nextTick(() => {
    if (obj) {
      form.value.detailList[index].isShow = true
      form.value.detailList[index].itemInfo = obj.drugName;
      form.value.detailList[index].drugInfoId = obj.drugInfoId;
      form.value.detailList[index].drugName = obj.drugName;
      form.value.detailList[index].drugCode = obj.drugCode;
      form.value.detailList[index].orgId = obj.orgId;
      form.value.detailList[index].packageSpec = obj.packageSpec;
      form.value.detailList[index].currentSpec = obj.currentSpec;
      form.value.detailList[index].currentUnits = obj.currentUnits;
      form.value.detailList[index].packageUnits = obj.packageUnits;
      form.value.detailList[index].units = obj.units;
      form.value.detailList[index].tradePrice = obj.tradePrice;
      form.value.detailList[index].tradePriceShow = obj.tradePrice;
      form.value.detailList[index].retailPriceShow = obj.retailPrice;
      form.value.detailList[index].retailPrice = obj.retailPrice;
      form.value.detailList[index].packSize = obj.packSize;
      form.value.detailList[index].discount = "1";
      form.value.detailList[index].firmId = obj.firmId;
      form.value.detailList[index].firmName = obj.firmName;
      form.value.detailList[index].packageNum = obj.packageNum;
      form.value.detailList[index].drugPriceId = obj.drugPriceId;
      itemAutomatic.value.closePopover();
      itemAutomatic.value.itemNameFocus();
    }
  });
}

/**
 * 自动补全上边input获得焦点事件   待测试
 * @param _index
 * @param row
 */
function isShowItemNameFocus(_index: number, row: any) {
  row.isShow = false
  nextTick(() => {
    itemAutomatic.value.init()
    itemAutomatic.value.setItemName(row.drugName)
    itemAutomatic.value.focusInput()
  })
}

/** 供应商选择事件 */
function storageFromClick(obj) {
  // form.value.storageFrom = obj.id;
  form.value.storageFrom = obj.storageId;
}

/**
 * 申领科室
 * @param obj
 */
function storageIdClick(obj) {
  form.value.storageId = obj.id;
}

// 监控科室是否改变，并查询入库方式
// watch(() => currentSelectDept, () => {
//   getStoreroomDistinguishFun()
//
// }, {deep: true, immediate: true})

/** 根据科室id 出入库类型获取库房对应的出入库方式 */
// function getStoreroomDistinguishFun() {
//   if (currentSelectDept) {
//     typeList.value = [];
//     let param = {
//       storageCode: currentSelectDept,
//       orgId: queryParams.value.orgId,
//       inoutType: "1",
//       dictType: "drug_storage_type",
//     };
//     getStoreroomDistinguish(param).then((res: any) => {
//       res.data.forEach((item: any) => {
//         typeList.value.push(item.sysDictData);
//       });
//     });
//   }
// }

/** 查询药品申领暂存列表 */
function getList() {
  selectPageDrugApplyFor(proxy.$addDateRange(queryParams.value, dateRange.value)).then((response: any) => {
    stagingList.value = response.rows;
    total.value = response.total;
  });
}

async function getListDetail() {
  await listDrugApplyFor(detailQuery.value).then((response: any) => {
    stagingListDetail.value = response.data;
    stagingListDetail.value.forEach((item: any) => {
      if(item.packSize === '2'){
        item.quantity = item.quantity / item.packageNum;
      }
    })
  });
  return stagingListDetail.value;
}

/**
 * 暂存列表弹出框关闭事件
 * type: 1 清空applyNo applyTime
 */
function temporaryStorageClose() {
  debugger
  // 暂存列表
  stagingList.value = [];
  // 暂存申领明细列表
  stagingListDetail.value = [];
  if (isEmptyApplyInfo.value) {
    form.value.detailListSave = [];
    form.value.applyNo = undefined
    form.value.applyTime = undefined
  }
  open.value = false;
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  handleQuery();
}

/**
 * 暂存列表 引入
 * @param row
 */
async function bringIn(row) {
  if (form.value.detailListSave.length > 0) {
    return ElMessage.error("已添加列表存在未保存的数据，请暂存或者确认发送后再引入当前数据");
  }
  detailQuery.value.applyNo = row.applyNo;
  detailQuery.value.orgId = row.orgId;
  let stagingListDetail = await getListDetail();
  form.value.importClass = row.importClass;
  form.value.isStaging = row.isStaging;
  form.value.applyNo = row.applyNo;
  form.value.id = row.id;
  // 设置申领科室
  nextTick(() => {
    storageIdDeptRef.value.setValue(row.storageId);
    form.value.storageId = row.storageId;
    // 设置供货单位
    drugStorageDeptRef.value.setValue(row.storageFrom);
    form.value.storageFrom = row.storageFrom;
  });
  // 设置申领明细
  stagingListDetail.forEach((obj) => {
    let detail: any = {};
    detail.itemInfo = obj.drugName;
    detail.drugInfoId = obj.drugInfoId;
    detail.applyId = obj.applyId;
    detail.drugName = obj.drugName;
    detail.drugCode = obj.drugCode;
    detail.orgId = obj.orgId;
    detail.packageSpec = obj.packageSpec;
    detail.currentSpec = obj.packageSpec;
    detail.packageUnits = obj.packageUnits;
    detail.currentUnits = obj.packageUnits;
    if(obj.packSize === '2'){
      detail.currentSpec = obj.packageSpec;
      detail.currentUnits = obj.packageUnits;
    }else{
      detail.currentSpec = obj.minSpec;
      detail.currentUnits = obj.minUnits;
    }
    detail.packageNum = obj.packageNum;
    detail.quantity = obj.quantity;
    detail.batchNo = obj.batchNo;
    detail.location = obj.location;
    detail.firmName = obj.firmName;
    detail.firmId = obj.firmId;
    detail.remarks = obj.remarks;
    detail.trackCodes = form.value.trackCodes;
    detail.packSize = obj.packSize;
    form.value.detailListSave.push(detail);
  });
  isEmptyApplyInfo.value = false;
  temporaryStorageClose()
}


/** 暂存列表主记录点击事件 */
async function stagingMaster(row, _index) {
  detailQuery.value.applyNo = row.applyNo;
  detailQuery.value.orgId = row.orgId;
  await getListDetail();
}

/** 新增按钮操作 */
function handleAdd() {
  if (!form.value.importClass) {
    return ElMessage.error("入库方式不能为空");
  }
  if (!form.value.storageId) {
    return ElMessage.error("申领科室不能为空");
  }
  if (!form.value.storageFrom) {
    return ElMessage.error("供货单位不能为空");
  }
  (formRef.value as any).validate((valid) => {
    // importInvoiceElMessageBox()
    if (valid) {
      if (form.value.detailList[0].packSize === '2') {
        form.value.detailList[0].retailPriceMin = (form.value.detailList[0].retailPriceShow / form.value.detailList[0].packageNum).toFixed(4)
        form.value.detailList[0].tradePriceMin = (form.value.detailList[0].tradePriceShow / form.value.detailList[0].packageNum).toFixed(4)
      } else {
        form.value.detailList[0].retailPriceMin = form.value.detailList[0].retailPriceShow
        form.value.detailList[0].tradePriceMin = form.value.detailList[0].tradePriceShow
        form.value.detailList[0].retailPrice = (form.value.detailList[0].retailPriceShow * form.value.detailList[0].packageNum).toFixed(2)
        form.value.detailList[0].tradePrice = (form.value.detailList[0].tradePriceShow * form.value.detailList[0].packageNum).toFixed(2)
      }
      // 添加到已编辑列表
      form.value.detailListSave.push(form.value.detailList[0]);
      // 删除当前编辑列表数据
      form.value.detailList = [{expireDate: "", discount: "1"}];
      nextTick(() => {
        tableBodyList.value = [];
        itemAutomatic.value.setItemName("");
      });
    }
  });
}

/** 修改按钮操作 */
function handleUpdate(row, index) {
  if (form.value.detailList[0].itemInfo) {
    ElMessageBox.confirm(
      "编辑列表存在未保存的药品数据，继续编辑将会替换编辑列表中的数据，确定要继续嘛？",
      "提示",
      {
        confirmButtonText: "替换编辑",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        form.value.detailList = [{expireDate: "", discount: "1"}];
        form.value.detailList[0] = row;
        form.value.detailListSave.splice(index, 1);
        nextTick(() => {
          itemAutomatic.value.setItemName(row.drugName);
        });
      })
      .catch(() => {
      });
  } else {
    form.value.detailList = [{expireDate: "", discount: "1"}];
    console.log("row", row)
    form.value.detailList[0] = row;
    form.value.detailListSave.splice(index, 1);
    nextTick(() => {
      itemAutomatic.value.setItemName(row.drugName);
    });
  }
}

/** 暂存 */
function temporaryStorage() {
  form.value.isStaging = "Y";
  form.value.confirmType = "4";
  save();
}

/** 最终提交 */
function lastSave() {
  form.value.isStaging = "N";
  form.value.confirmType = "2";
  save();
}

function save() {
  if (form.value.detailListSave.length <= 0) {
    return ElMessage.error("没有药品明细，不能提交");
  }
  ElMessageBox.confirm(
    `${form.value.isStaging === "Y" ? "确认要进行暂存吗？" : "确定要发送吗？"}`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(() => {
      form.value.orgId = queryParams.value.orgId;
      buttonLoading.value = true;
      let i = 0;
      form.value.detailListSave.forEach((item: any) => {
        i++;
        if (item.packSize === '2') {
          item.quantity = item.quantity * item.packageNum;
        }
        item.importClass = form.value.importClass;
        item.serialNumber = i;
        item.confirmType = form.value.confirmType;
      });
      buttonLoading.value = true;
      console.log("form.value", form.value)

      addDrugApplyFor(form.value).then(() => {
        // 清空入库发票号
        form.value.invoiceNo = ""
        if (form.value.isStaging === "Y") {
          ElMessage.success("暂存成功");
        } else {
          ElMessage.success("申领发送成功");
        }
        form.value.detailListSave = [];
      })
        .finally(() => {
          buttonLoading.value = false;
        });
    })
    .catch(() => {
      ElMessage.info("已取消操作");
    });
}

/** 暂存列表弹出框 */
function temporaryStorageTableClick() {
  open.value = true;
  isEmptyApplyInfo.value = true;
  queryParams.value.isStaging = "Y";
  getList();
}

/** 编辑列表删除按钮操作 */
function handleDelete(row, index) {
  ElMessageBox.confirm('是否确认删除药品"' + row.drugName + '"的数据？', {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      if (row.applyId) {
        delDrugApplyFor(row.applyId).then(() => {
          form.value.detailListSave.splice(index, 1);
        })
      } else {
        form.value.detailListSave.splice(index, 1);
      }
      ElMessage.success("删除成功");
    })
}

function deleteMaster(row: any) {
  ElMessageBox.confirm('是否确认删除暂存数据？',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    delDrugApplyForByApplyNo(row.applyNo, row.orgId).then(() => {
      getList();
      stagingListDetail.value = []
      ElMessage.success("删除成功");
    })
  })
}
</script>

<script lang="ts">
export default {
  name: "DrugImportMaster"
}
</script>

<style scoped>
:deep(.el-top) {
  background-color: rgb(212, 211, 211);
  border-radius: 5px 5px 5px 5px;
  margin: -5px 3px 5px 3px;
  height: 44px;
}

:deep(.dept-tree-label) {
  margin-right: -77px;
  margin-top: 6px;
  width: 18%;
}

:deep(.vue-treeselect__input-container) {
  height: 26px !important;
}

.account_type {
  font-weight: bold;
  color: rgb(30, 30, 30);
  float: left;
  width: 6%;
  /*margin-top: 6px;*/
}

:deep(.cell .el-tag) {
  margin: 0 -10px 0 -10px;
}

:deep(.el-input__wrapper) {
  background-color: #ff000017;
}

</style>
